﻿#if (PocketPC || Smartphone || WindowsCE)
using System;
using System.Collections.Generic;
using System.Text;

namespace RaisingStudio.Data.Common.Converters
{
    public class EnumConverter : IDbTypeConverter
    {
        private System.Type _type;

        public EnumConverter(System.Type type)
        {
            this._type = type;
        }

        #region IDbTypeConvertermember

        public object ConvertFromDbType(object value)
        {
            if (value is string)
            {
                try
                {
                    string str = (string)value;
                    if (str.IndexOf(',') != -1)
                    {
                        long num = 0L;
                        foreach (string str2 in str.Split(new char[] { ',' }))
                        {
                            num |= Convert.ToInt64((Enum)Enum.Parse(this._type, str2, true));
                        }
                        return Enum.ToObject(this._type, num);
                    }
                    return Enum.Parse(this._type, str, true);
                }
                catch (Exception exception)
                {
                    throw new FormatException(string.Format("ConvertInvalidPrimitive", new object[] { (string)value, this._type.Name }), exception);
                }
            }
            return null;
        }

        public object ConvertToDbType(object value)
        {
            if (value != null)
            {
                if (!this._type.IsDefined(typeof(FlagsAttribute), false) && !Enum.IsDefined(this._type, value))
                {
                    throw new ArgumentException(string.Format("EnumConverterInvalidValue", new object[] { value.ToString(), this._type.Name }));
                }
                return Enum.ToObject(this._type, value);
            }
            if (!this._type.IsDefined(typeof(FlagsAttribute), false))
            {
                return new Enum[] { ((Enum)Enum.ToObject(this._type, value)) };
            }
            return null;
        }

        #endregion
    }
}
#else
using System;
using System.Collections.Generic;
using System.Text;

namespace RaisingStudio.Data.Common.Converters
{
    public class EnumConverter : IDbTypeConverter
    {
        private System.Type _type;
        private System.ComponentModel.EnumConverter _enumConverter;

        public EnumConverter(System.Type type)
        {
            this._type = type;
            this._enumConverter = new System.ComponentModel.EnumConverter(this._type);
        }

#region IDbTypeConvertermember

        public object ConvertFromDbType(object value)
        {
            return this._enumConverter.ConvertFromString(value as string);
        }

        public object ConvertToDbType(object value)
        {
            return this._enumConverter.ConvertToString(value);
        }

#endregion
    }
}
#endif
